package com.yjy.fuyao.message.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yjy.fuyao.message.entity.Event;
import com.yjy.fuyao.message.entity.Message;
import com.yjy.fuyao.message.event.EventProducer;
import com.yjy.fuyao.message.service.MessageService;
import com.yjy.fuyao.utils.result.R;
import com.yjy.fuyao.utils.result.ResponseEnum;
import com.yjy.fuyao.utils.util.JwtUtils;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 网站信息 前端控制器
 * </p>
 *
 * @author yjy
 * @since 2022-01-02
 */
@RestController
@RequestMapping("/service/message")
public class MessageController {

    @Resource
    private MessageService messageService;

    @Resource
    private EventProducer producer;

    @GetMapping(value = "/msgList/{page}/{limit}")
    public R msgListByUid(@ApiParam(name = "page", value = "当前页码", required = true)
                             @PathVariable Long page,

                         @ApiParam(name = "limit", value = "每页记录数", required = true)
                             @PathVariable Long limit,

                         HttpServletRequest request){
        Page<Message> messagePage = new Page<>(page, limit);
        String userId = JwtUtils.getUserIdByJwtToken(request);
        if(userId == ""){
            return R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
        }
        Map<String,Object> map = messageService.pageListByUid(messagePage,userId);
        return R.ok().data(map);
    }

    @PutMapping(value = "/readMsg")
    public R readMsg(HttpServletRequest request){
        String userId = JwtUtils.getUserIdByJwtToken(request);
        if(userId == ""){
            return R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
        }
        messageService.readMsg(userId);
        return R.ok();
    }

    @PostMapping(value = "/sendSysMsg")
    public R sendSysMsg(@RequestBody Event event){
        System.out.println("开始发送消息...");
        producer.sendMessage(event);
        return R.ok();
    }

    @GetMapping(value = "/getNewMsg")
    public R getNewMsg(HttpServletRequest request){
        String userId = JwtUtils.getUserIdByJwtToken(request);
        if(userId == ""){
            return R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
        }
        boolean result = messageService.getNewMessageByUId(userId);
        return R.ok().data("result",result);
    }

}

